import axios from "axios";
import { Message } from "element-ui";
import store from "./../store/index";

const service = axios.create({
  baseURL: "http://192.168.33.201:3000",
  timeout: 5000,
});

service.interceptors.request.use(
  (config) => {
    const token = store.getters.accessToken;
    if (token) {
      config.headers["Authorization"] = "Bearer " + token;
    } else {
      console.error('Token not found in store');
    }
    return config;
  },
  (error) => {
    console.error("请求错误:", error);
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  response => {
    if (response.status >= 200 && response.status < 300) {
      return response.data;
    } else {
      Message({
        message: response.data.message || "请求错误",
        type: "error",
        duration: 5000
      });
      return Promise.reject(new Error(response.data.message || "请求错误"));
    }
  },
  async error => {
    const originalRequest = error.config;
    if (error.response && error.response.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      try {
        const newToken = await store.dispatch('refreshAccessToken');
        originalRequest.headers["Authorization"] = "Bearer " + newToken;
        return service(originalRequest);
      } catch (refreshError) {
        console.error("刷新Token失败:", refreshError);
        return Promise.reject(refreshError);
      }
    }
    Message({
      message: error.message || "请求失败",
      type: "error",
      duration: 5000
    });
    return Promise.reject(error);
  }
);

export default service;
